Ext.define('Triends.view.Join', {
	extend: 'Ext.Panel',
	xtype: 'join',
	id: 'join',
	alias: 'join',
	config: {
	    styleHtmlContent: true,
	    scrollable: false,
	    listeners: {
	    	deactivate: function() {
	    		this.destroy();
	    	}
	    },
    	items: [
    	{
			xtype: 'panel',
			layout: 'hbox',
			width: "100%",
			items: [{
 				xtype: 'fieldset',
 				layout: 'hbox',
 				title: 'Theme',
				width: '92%',
 				items: [
 					{
		 				 xtype: 'selectfield',
		 				 style: 'border:3px inset',
		 				 flex: 9,
		 				 usePicker: false,
		 				 id: 'jointheme',
		 				 options: [
		 				 	{text: ' ', value: ' '},
						 	{text: '식사', value: 1},
						 	{text: '술', value: 2},
						 	{text: '야경', value: 3},
						 	{text: '공연 관람', value: 4},
						 	{text: '쇼핑', value: 5},
						 	{text: '클러빙', value: 6},
						 	{text: '전체', value: 7}
		 				 ],
		 				 listeners:{
		 				 	change: function(selectbox,newValue,oldValue){
		 				 		var themevalue = Ext.getCmp('jointheme').getValue();
		 				 		Ext.getCmp('jointhemeimage').setHidden(false);
		 				 		Ext.getCmp('jointhemeimage').setSrc('resource/images/'+themevalue+'.png');	
		 				 	}
		 				 }
				}] 
			},
			{
				xtype: 'spacer',
				width: '2%'
			},
			{
				xtype: 'panel',
				docked: 'right',
				width: 48,
				height: 48,
				style: 'margin-top:35px',
				items: [{
					xtype: 'image',
					id: 'jointhemeimage',
					width: 48,
					height: 48
				}]
			}]
		},
		{
	    		xtype: 'fieldset',
	    		title: '카카오톡  ID',
	    		instructions: '카카오톡 ID는 같은 Ting(모임)의 멤버들에게만 보여집니다.',
		    	items: [{
	    			xtype: 'textfield',
	    			style: 'border:3px inset',
		    		id : 'joincacao',
	    	        maxLength: 200
	        	}]
    	},
    	{
			xtype: 'button',
			text: 'Create a Account',
			handler: function(){
				
				var joindata = Ext.getCmp('join').getData();
				var cacao = Ext.getCmp('joincacao').getValue();
				var jointheme = Ext.getCmp('jointheme').getValue();

				Ext.Viewport.setMasked({
					xtype: 'loadmask',
					message: '회원가입 중입니다.',
					indicator: true
				});
            	navigator.geolocation.getCurrentPosition(function(position){
            		
            		var userlat = position.coords.latitude;
            		var userlng = position.coords.longitude;
            		
            		Ext.data.JsonP.request({
            		url: 'http://itscreater.cafe24.com/Triends/Join.jsp',
            		params: {
            			id: joindata.id,
   						name:joindata.name, 
   						email:joindata.email,
   						gender:joindata.gender,
   						age: joindata.age,
   						cacao:cacao,
   						jointheme: jointheme,
   						userlat: userlat,
   						userlng: userlng
            		},
//            		callbackKey: 'callback',
            		success: function(response) {
            				Ext.Viewport.setMasked(false);
							Ext.Viewport.setMasked({
								xtype: 'loadmask',
								message: 'Loading...',
								indicator: true
							});
        					Tutorial()
            				
        					var main;
      						if (Ext.typeOf(Ext.getCmp('main')) == 'object') {
            					main = Ext.getCmp('main')
	        				} else {
    	    					main = Ext.create('mainpage');
        					}
        					Ext.Viewport.setActiveItem(main);
							Triends.app.getHistory().add(Ext.create('Ext.app.Action', {url: 'mainpage'}));
            				
            				var UserStore = Ext.getStore('UserStore');
							UserStore.getProxy().setExtraParams({id: joindata.id});
        					UserStore.load({
	        					callback: function(records, operation, success) {
									var userlat = UserStore.getAt(0).data.UserLat
							       	var userlng = UserStore.getAt(0).data.UserLng
							       	var userid = UserStore.getAt(0).data.ID;
									var usertheme = UserStore.getAt(0).data.UserTheme;
							       	
									if (usertheme == 1) {  // usertheme이 1인 경우 triendslisttheme에서 change이벤트가 발생하지 않기 때문.
										Ext.getCmp('tingthemeimg').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
										Ext.getCmp('triendstheme').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
										var userthemepanel = Ext.getCmp('userthemepanel');
										userthemepanel.setSrc('resource/images/'+usertheme+'.png');
									} else {
										Ext.getCmp('triendslisttheme').setValue(usertheme);
									}
	        						
									TriendsStore.setProxy({
										type: "jsonp",
										url: 'http://itscreater.cafe24.com/Triends/TriendsList.jsp',
										callbackkey: 'callback',
										extraParams: {
											userid: userid,
											userlat:userlat,
							    			userlng:userlng,
							    			usertheme: usertheme
										},
										pageParam: 'pages',
										limitParam: 'rpp',
										reader: {
											type: "json",
											rootProperty: "results",
											totalProperty: "total"
										}
									});
												
									tingStore.setProxy({
										type: "jsonp",
										url: 'http://itscreater.cafe24.com/Triends/TingList.jsp',
										extraParams: {
											userlat: userlat, 
											userlng:userlng, 
											usertheme: usertheme
										},
										callbackkey: 'callback',
										pageParam: 'pages',
										limitParam: 'rpp',
										reader: {
											type: "json",
											rootProperty: "results",
											totalProperty: "total"
										}
									});
	        						
									TriendsStore.loadPage(1, {
										callback: function() {
											tingStore.loadPage(1)
											var userimg = Ext.getCmp('userimg');
											userimg.setHtml("<img src='https://graph.facebook.com/"+userid+"/picture?width=130&height=130'>");
									
											var userHOSTtingStore = Ext.getStore('userHOSTtingstore');
											var userATTENDtingStore = Ext.getStore('userATTENDtingstore');	
											
											Ext.data.JsonP.request({
												url: 'http://itscreater.cafe24.com/Triends/UserHostTing.jsp',
												params:{
													id: userid, 
													userlat: userlat, 
													userlng: userlng, 
													usertheme: usertheme
												},
												callbackKey: 'callback',
												success: function(result) {
													for(i=0;i<result.length;i++){
														var date = result[i].DATE.split(' ')[0];
														var hour = result[i].DATE.split(' ')[1].substr(0,2);
														var minute = result[i].DATE.split(' ')[1].substr(2);
														var ampm;
														if(hour >= 12){
															hour = hour-12;
															ampm = "PM"
														} else{
															ampm = "AM"
														}
														var finaldate = date+" "+ampm+" "+hour+""+minute;
														result[i].AMPMDATE = finaldate; 
													}
													userHOSTtingStore.setData(result);
													
													Ext.data.JsonP.request({
														url: 'http://itscreater.cafe24.com/Triends/UserAttendTing.jsp',
														params:{
															id: userid, 
															userlat: userlat, 
															userlng: userlng, 
															usertheme: usertheme
														},
														callbackKey: 'callback',
														success: function(result) {
															for(i=0;i<result.length;i++){
																var date = result[i].DATE.split(' ')[0];
																var hour = result[i].DATE.split(' ')[1].substr(0,2);
																var minute = result[i].DATE.split(' ')[1].substr(2);
																var ampm;
																if(hour >= 12){
																	hour = hour-12;
																	ampm = "PM"
																} else{
																	ampm = "AM"
																}
																var finaldate = date+" "+ampm+" "+hour+""+minute;
																result[i].AMPMDATE = finaldate;
															}
															userATTENDtingStore.setData(result);
															
															var msgStore = Ext.getStore('msgstore');
															msgStore.getProxy().setExtraParams({id: userid});
															msgStore.load();
											
															window.GCM.register("157631774206", "GCM_Event", GCM_Success, GCM_Fail );
															
															setTimeout(function() {
																Ext.Viewport.setMasked(false);
															}, 500);
														}
													});
												}
											});									
										}
									});
	        					}
							});
	            		}
    	        	});
            		
            		
            		
            		
            		}, function(error) {console.log(error.code+error.message)});
            	
            	
			}
 		}]
	}
});

function Tutorial() {
	var tutorial = Ext.Viewport.add({
		xtype: 'carousel',
		fullscreen: true,
		width: '100%',
		height: '100%',
		zIndex: 5,
		items: [
			{
				xtype: 'panel',
	            style: 'background-color: #FFCC33;',
	            layout: 'vbox',
	            items: [
	            {
	            	xtype: 'panel',
	            	height: 120,
	            	width: '100%',
	            	style: 'position:absolute;top:50%;margin-top:-60px;text-align:center;',
	            	html: '<font size="4"><b>Triends를 <br>제대로 사용하기 위해 <br>반드시 알아야 할 <br><font size="5"><u>네 가지!</u></font>를 알려드립니다.</b></font>'
	            }]
			},
	        {
	        	xtype: 'panel',
	            style: 'background-color: #FFCC33;',
	            layout: 'vbox',
	            items: [
	            {
	            	xtype: 'panel',
	            	height: 110,
	            	width: '100%',
	            	style: 'position:absolute;top:50%;margin-top:-55px;text-align:center;',
	            	html: '<font size="6"><b><font size="4">첫째,</font><br>Ting = 모임</b></font>'
	            }]
	        },
	        {
	            xtype: 'panel',
	            style: 'background-color: #FFCC33',
	            layout: 'vbox',
	            items: [{
	            	xtype: 'panel',
	            	height: 110,
	            	width: '100%',
	            	style: 'position:absolute;top:50%;margin-top:-55px;text-align:center',
	            	html: '<font size="6"><b><font size="4">둘째,</font><br>Triends = 여행자</b></font>'
	            }]
	        },
	        {
	            xtype: 'panel',
	            style: 'background-color: #FFCC33',
	            layout: 'vbox',
	            items: [{
	            	xtype: 'panel',
	            	height: 110,
	            	width: '100%',
	            	style: 'position:absolute;top:50%;margin-top:-55px;text-align:center',
	            	html: '<font size="6"><b><font size="4">셋째,</font><br>T-fi = 만날 확률</b></font>'
	            }]
	        },
	        {
	            xtype: 'panel',
	            style: 'background-color: #FFCC33',
	            layout: 'vbox',
	            items: [{
	            	xtype: 'panel',
	            	height: 110,
	            	width: '100%',
	            	style: 'position:absolute;top:50%;margin-top:-55px;text-align:center',
	            	html: '<font size="5"><b><font size="4">넷째,</font><br>Triends는 <br>사용자 간의 신뢰를 위해<br>Facebook 계정을 연동합니다.</b></font>'
	            }]
	        },
	        {
	        	xtype: 'panel',
	        	style: 'background-color: #FFCC33;text-align:center;',
	        	layout: 'vbox',
	        	items: [
	        	{
	        		xtype: 'panel',
	        		style: 'position:absolute;top:50%;margin-top:-110px',
	        		width: '100%',
	        		height: 220,
	        		items: [
	        		{
		        		xtype: 'panel',
		        		html: "<font size='4'><b>이제<font size='5'> Triends</font>에서<br><br>'함께하는 여행'을 <br><br>시작해보세요!</b></font>"	
		        	},
		        	{
		        		xtype: 'panel',
		        		style: 'margin-top:40px',
		        		items:[{
		        			xtype: 'button',
		        			centered: true,
		        			width: 100,
		        			text: '시작',
		        			handler: function(){
		        				tutorial.hide();
		        			}
		        		}]
		        	}]
	        	}]
	        }]
	});
	tutorial.show();
}